package com.base.core.context.processor;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

import com.base.core.context.utils.git.GiHubApiUtils;
import com.gitee.magic.core.exception.ApplicationException;

/**
 * 
 * @author start
 *
 */
@Order(1)
public class GitHubConfigureEnvironmentPostProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		String projectName=environment.getRequiredProperty("spring.application.name");
		String active=environment.getRequiredProperty("spring.profiles.active");
		
		String repo=environment.getRequiredProperty("github.repo");
		String owner=environment.getRequiredProperty("github.owner");
		String privateToken=environment.getRequiredProperty("github.privateToken");
		String branchName=environment.getRequiredProperty("github.branchName");
		
		String content=GiHubApiUtils.loadString(owner, repo, branchName, projectName, active, privateToken);
		Properties props=new Properties();
		try {
			props.load(new ByteArrayInputStream(content.getBytes()));
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
		environment.getPropertySources().addFirst(new PropertiesPropertySource("remote_config", props));
	}
	
}
